package za.org.jcicada.cfgmngr.impl;

import za.org.jcicada.cfgmngr.ISystemObserver;
import za.org.jcicada.cfgmngr.ISystemSubject;
import za.org.jcicada.cfgmngr.SystemSetType;
import za.org.jcicada.cfgmngr.messages.AttachReply;
import za.org.jcicada.cfgmngr.messages.DetachReply;
import za.org.jcicada.cfgmngr.messages.SystemEventInform;
import za.org.jcicada.comms.IConnection;
import za.org.jcicada.comms.impl.MessagingBase;
import za.org.jcicada.genss.SystemURN;
import za.org.jcicada.genss.messages.Result;

public class SystemsMessaging extends MessagingBase {

    /**
     * Handle to system subject for invoking methods on.
     */
    ISystemSubject systemSubject;

    /**
     * Handle to callback object for messages from the subject to the observer.
     */
    ISystemObserver observer;

    public SystemsMessaging(IConnection connection, ISystemSubject systemSubject) {
        super(connection);
        this.systemSubject = systemSubject;
        observer = new Responder();
    }

	public void onClose() throws Exception {
        systemSubject.informDisconnect(observer);
	}
	
	public ISystemObserver getObserver() {
		return observer;
	}

    public void cfgmngrAttachRequest(za.org.jcicada.cfgmngr.messages.AttachRequest msg) {
        systemSubject.requestAttach(observer);
    }

	public void cfgmngrDetachRequest(za.org.jcicada.cfgmngr.messages.DetachRequest msg) {
		systemSubject.requestDetach(observer);
	}

    /**
     * Implementation of IConfigurationClient that sends messages back to a
     * katcomms connection.
     */
    public class Responder extends MessagingBase.ResponderBase implements ISystemObserver {

		public void informSystemEvent(SystemURN systemURN, SystemSetType type, Event event) {
			sendMessage(new SystemEventInform(systemURN, type, event));
		}

		public void replyAttach(Result result) {
			sendMessage(new AttachReply(result));
		}

		public void replyDetach(Result result) {
			sendMessage(new DetachReply(result));
		}
    
    }
}
